// 文件转base64
export function getBase64 (file) {
	return new Promise((resolve, reject) => {
		const reader = new FileReader()
		reader.readAsDataURL(file)
		reader.onload = () => resolve(reader.result)
		reader.onerror = error => reject(error)
	})
}
// base64转文件
export function base64ImgtoFile (dataurl, filename = 'file') {
	if (typeof dataurl !== 'string') {
		return
	}
	//将base64格式分割：['data:image/png;base64','XXXX']
	const arr = dataurl.split(',')
	// .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
	// image/png
	const mime = arr[0].match(/:(.*?);/)[1]  //image/png
	//[image,png] 获取图片类型后缀
	const suffix = mime.split('/')[1] //png
	const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
	let n = bstr.length
	const u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	return new File([u8arr], `${filename}.${suffix}`, {
		type: mime
	})
}
// 匹配word内容中所有图片
export function extractImageDataFromRtf(rtfData) {
	if ( !rtfData ) {
		return []
	}

	const regexPictureHeader = /{\\pict[\s\S]+?(\\bliptag-?\d+)?(\\blipupi-?\d+)?{\\\*\\blipuid\s?[\da-fA-F]+[\s}]*?/
	const regexPicture = new RegExp( '(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}', 'g' )
	// /(?:({\\pict[\s\S]+?(\\bliptag-?\d+)?(\\blipupi-?\d+)?{\\\*\\blipuid\s?[\da-fA-F]+[\s}]*?))([\da-fA-F\s]+)\}/g
	const images = rtfData.match( regexPicture )
	const result = []
	if ( images ) {
		for ( const image of images ) {
			let imageType = false

			if ( image.includes( '\\pngblip' ) ) {
				imageType = 'image/png'
			} else if ( image.includes( '\\jpegblip' ) ) {
				imageType = 'image/jpeg'
			}

			if ( imageType ) {
				result.push( {
					hex: image.replace( regexPictureHeader, '' ).replace( /[^\da-fA-F]/g, '' ),
					type: imageType
				} )
			}
		}
	}

	return result
}
// 将图片转成base64
export function replaceImagesFileSourceWithInlineRepresentation(imageElements,imagesHexSources) {
	const srcs = []
	// Assume there is an equal amount of image elements and images HEX sources so they can be matched accordingly based on existing order.
	if ( imageElements.length === imagesHexSources.length ) {
		for ( let i = 0; i < imageElements.length; i++ ) {
			const newSrc = `data:${imagesHexSources[i].type};base64,${_convertHexToBase64(imagesHexSources[i].hex)}`
			srcs.push(newSrc)
		}
	}
	return srcs
}
function _convertHexToBase64(hexString){
	return btoa(hexString.match( /\w{2}/g)?.map( char => {
		return String.fromCharCode( parseInt( char, 16 ) )
	} ).join( '' ) )
}

// 获取视频宽高
export function getVideoDimensions(url) {
	return new Promise((resolve, reject) => {
		const video = document.createElement('video');
		video.onloadedmetadata = () => {
			resolve({ width: video.videoWidth, height: video.videoHeight });
		};
		video.onerror = (error) => {
			reject(error);
		};
		video.src = url;
	});
}

// 获取设备dpi
export function getDeviceDPI() {
	var dpi = 96; // 默认值 96dpi

	if (window.screen && window.screen.deviceXDPI && window.screen.logicalXDPI) {
		dpi = window.screen.deviceXDPI / window.screen.logicalXDPI * dpi;
	} else if (window.devicePixelRatio) {
		dpi = dpi * window.devicePixelRatio;
	}

	return dpi;
}

// 获取当前选中的文本大小
export const getSelectedTextSize = (editor) => {
	const { selection } = editor.state;
	const { from, to } = selection;

	const node = editor.state.doc.nodeAt(from);
	if (!node || !node.marks) {
		// 没有找到节点或者没有样式
		return null;
	}
	const fontSizeMark = node.marks.find(mark => mark.type.name === "textStyle");
	if (!fontSizeMark) {
		// 没有找到字体大小样式
		return null;
	}
	return fontSizeMark.attrs.fontSize;
}

/**
 * 获取本地缓存地址
 * @param base64
 * @return Promise
 */
export const getLocalTemplateUrl = (base64) => {
	return new Promise((resolve, reject) => {
		resolve(URL.createObjectURL(base64ImgtoFile(base64)))
	})
}
